#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
##########################################################################
#
# pmData.py
# Classe que s'encarrega de realitzar consultes i tractar les dades
# d'analitzadors PMxxx del fabricant Schneider-Electric.
#
# Tomeu Capó
#

import pickle,time
from modBusComm import *
from params import pmRegs

class pmData:
      def __init__(self, pmComm, vars, model):
          self.pmComm = pmComm
          self.variables = vars
          self.buidaLectura()
          self.logger = None
          self.rangs = {}
          self.lastError = ""
          self.lectura = {}

          if model in pmRegs.tRegs.keys():
             self.regsQuery = pmRegs.tRegs[model]
          else:
             raise KeyError, "Aquest model de PM no esta soportat!"
             return 

      def setVariables(self, vars):
          self.variables = vars

      def getDefs(self):
          return pickle.dumps(self.regsQuery)

      # Buida les darreres lectures fetes

      def buidaLectura(self):
          self.lastError = ""
          self.darreraLectura = {}
          for cmd in self.variables:
              self.darreraLectura[cmd] = []

      # Realitza una bateria de peticions a l'esclau
 
      def consulta(self):
          correcte = False
          for var in self.variables:
	      params = self.regsQuery[var]

              if self.pmComm.enviar(READ_WORDS, params[0], params[1]):
                 if self.pmComm.rebre():
                    correcte = True
                    factEscala = self.rangs[params[5]] if (params[5] in self.rangs) else params[3]
                    dades = [0 if float(v)>params[4] else (float(v)*factEscala) for v in self.pmComm.lastResponse]
                    self.darreraLectura[var].append(dades)
                    self.lectura[var] = dades
                 else:
                    self.lastError = self.pmComm.msgError()
                    self.logger.error(self.pmComm.msgError())
                    correcte = False
                    break

          return(correcte)  

      # Metode que ens torna el identificador del analitzador

      def identifica(self):
          retval = ''
          if self.pmComm.enviar(0x11, 0, 0):
             if self.pmComm.rebre():
                retval = self.pmComm.lastResponseB[2:]
                self.carregaRangs() 
             else:
                self.lastError = self.pmComm.msgError()
	        self.logger.error(self.pmComm.msgError())
         
          return(retval)

      def carregaRangs(self):
          peticionsRng = {}
          for var in self.variables:
              if self.regsQuery[var][5] in self.regsQuery:
                 pet = self.regsQuery[var][5]
                 peticionsRng[pet] = self.regsQuery[pet]
          
          for pt in peticionsRng:
	      params = self.regsQuery[pt]
              self.rangs[pt] = 0
              if self.pmComm.enviar(READ_WORDS, params[0], params[1]):
                 if self.pmComm.rebre():
                    self.rangs[pt] = pmRegs.factorEscala[str(self.pmComm.lastResponse[0])]

      def __str__(self):
          return pickle.dumps(self.lectura)

